//
//  SleepGroundChartView.swift
//  MYModule
//
//  Created by HFY on 2022/10/31.
//

import UIKit
import MYModule

public class SleepGroundChartView: View {
    
    /// 决定创建几个色的capview
    public let colors: [UIColor]
    
    public private(set) var capViews: [View] = []
    
    /// 按比例显示 capView, 如果 proportions长度小于capViews长度，多的capView 将会被隐藏
    public var proportions: [CGFloat] = [] {
        
        didSet {
            
           capViewLayouts()
            
        }
        
    }
   
    public init(colors: [UIColor]) {
        
        self.colors = colors
        super.init(frame: CGRect.zero)
       
        makeUI()
        
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    public override func makeUI() {
        super.makeUI()
        
        for color in colors {
            
            let capView = View()
            capView.backgroundColor = color
            addSubview(capView)
            capViews.append(capView)
            
        }
        
    }
    
  
    
    fileprivate func capViewLayouts() {
        
        self.layoutIfNeeded()
        
        var beforeCapView: View? = nil
        for (i, capView) in capViews.enumerated() {
            
            if i >= proportions.count {
                
                capView.isHidden = true
                
            } else {
                
                capView.isHidden = false
                let proportion = proportions[i]
                
                capView.snp.remakeConstraints { make in
                    make.left.right.equalToSuperview()
                    if let beforeCapView = beforeCapView {
                        make.bottom.equalTo(beforeCapView.snp.top)
                    } else {
                        make.bottom.equalToSuperview()
                    }
                    
                    make.height.equalTo(self.frame.height * proportion)
                    
                }
            }
            beforeCapView = capView
            
        }
    }

}
